<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >

  <div style="height: 50px;">
    <el-button @click="openDialog" :disabled="props.isDisabled">批量新增</el-button>
    <el-button @click="handleAdd" :disabled="props.isDisabled">添加明细</el-button>

    <InventoryForm ref="formRefAdd" :saleOrderId="props.saleOrderId" :warehouseId="props.warehouseId" @success="handleSuccess" />
    <InventoryForm2 ref="formRefAdd2" :saleOrderId="props.saleOrderId" :warehouseId="props.warehouseId" @success2="handleSuccess2" />

  </div>


    <el-table :data="formData" class="-mt-10px" style="height: 280px;" border>
      <el-table-column label="序号" type="index" width="100" />
   


      
      <el-table-column label="存货编码" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryCode`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryCode" placeholder="请输入存货编码"  @click="openDialog2($index)"   :disabled="props.isDisabled" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="存货名称" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryName" placeholder="请选择存货名称"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="规格型号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventorySpecModel`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventorySpecModel" placeholder="请输入规格型号"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="单位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.inventoryUnitName`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.inventoryUnitName" placeholder="请输入单位"  @click="openDialog2($index)"   :disabled="true" />
          </el-form-item>
        </template>
      </el-table-column>

      <el-table-column label="批号" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.batchCode`"  class="mb-0px!">
            <el-input v-model="row.batchCode" placeholder="请输入批号" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="货位" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.locationName`"  class="mb-0px!">
            <el-input v-model="row.locationName" placeholder="请输入货位" :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.quantity`" :rules="formRules.required" class="mb-0px!">
            <el-input v-model="row.quantity" placeholder="请输入数量"  @input="calculateValues($index)" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>



      <el-table-column label="库存数量" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.maxQuantity`"  class="mb-0px!">
            <el-input v-model="row.maxQuantity" placeholder="最大数量"   :disabled="true"/>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.remark`"  class="mb-0px!">
            <el-input v-model="row.remark" placeholder="请输入备注" :disabled="props.isDisabled"/>
          </el-form-item>
        </template>
      </el-table-column>


      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link>—</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-form>

</template>
<script setup lang="ts">
import { Rdrecord32Api } from '@/api/wms/rdrecord32'
import { ElMessage } from 'element-plus';
import { StockApi, StockLogVO } from '@/api/wms/stock'
import InventoryForm from './Rdrecords32StockLogForm.vue';
import InventoryForm2 from './Rdrecords32StockLogForm2.vue';

import { SaleOrderApi, SaleOrderVO } from '@/api/wms/saleorder'

const params = reactive({

  saleOrderId:0,
  warehouseId:0
})

const props = defineProps<{
  pid: number | undefined  // 主表ID（主表的关联字段）
  saleOrderId:number | undefined 
  isDisabled: boolean | undefined // 是否禁用表单           
  warehouseId:number | undefined
}>()
const formLoading = ref(false) // 表单的加载中
const formData = ref([])
const formRules = reactive({
  required: [{ required: true, message: '不能为空', trigger: 'blur' }],

})
const formRef = ref() // 表单 Ref
const stockLogVOList = ref([] as StockLogVO[]); // 存货列表
const selectLoading = ref(false) // 表单的加载中

//查询存货
// const remoteInventory = async () => {
//   if(props.saleOrderId==undefined)
//   {
//     ElMessage.warning(`请先选择采购订单`);
//   }else if(props.warehouseId==undefined)
//   {
//     ElMessage.warning(`请先选择仓库`);
//   }
  
//   else{
//     params.saleOrderId=props.saleOrderId
//     params.warehouseId=props.warehouseId
//     stockLogVOList.value =await StockApi.findAboutSaleStockLog(params);
//   }
// }

/** 监听主表的关联字段的变化，加载对应的子表数据 */
watch(
  () => props.pid,
  async (val) => {
    // 1. 重置表单
    formData.value = []
    // 2. val 非空，则加载数据
    if (!val) {
      return;
    }
    try {
      formLoading.value = true
      const initialData  = await Rdrecord32Api.getRdrecords32ListByPid(val)
      formData.value = await Promise.all(initialData.map(async (item) => {
        if (item.stockId) {
          const inventory = await StockApi.getStock(item.stockId);
          return {
            ...item,
            inventoryName: inventory.inventoryName,
            inventoryCode: inventory.inventoryCode,
            inventoryUnitName: inventory.inventoryUnitName,
            inventorySpecModel: inventory.inventorySpecModel,
            batchCode: inventory.batchCode,
            locationName:inventory.locationName,
            maxQuantity:inventory.qty+item.quantity,
          };
         
        }
      
        return item;
      
      }));

    } finally {
      formLoading.value = false
    }
  },
  { immediate: true }
)
/** 新增按钮操作 */
const handleAdd = () => {
  const row = {
    id: undefined,
    pid: undefined,
    sourceOrderId: undefined,
    inventoryId: undefined,
    batch: undefined,
    locationId: undefined,
    quantity: undefined,
    taxRate: undefined,
    price: undefined,
    taxPrice: undefined,
    money: undefined,
    tax: undefined,
    sum: undefined,
    remark: undefined,
    sourceBatch: undefined,
    stockId: undefined,
    
  }
  row.pid = props.pid
  formData.value.push(row)
}

/** 删除按钮操作 */
const handleDelete = (index) => {
  formData.value.splice(index, 1)
}

/** 表单校验 */
const validate = () => {
  return formRef.value.validate()
}

/** 表单值 */
const getData = () => {
  return formData.value
}

// /** 处理存货名称选择变化 */
// const handleInventoryChange = (value, row) => {
//   const selectedInventory = stockLogVOList.value.find(item => item.id === value);
//   if (selectedInventory) {
//     row.stockId = selectedInventory.id;
//     row.inventoryName = selectedInventory.inventoryName;
//     row.inventoryCode = selectedInventory.inventoryCode;
//     row.inventoryUnitName = selectedInventory.inventoryUnitName;
//     row.inventorySpecModel = selectedInventory.inventorySpecModel;
//     row.taxRate=selectedInventory.irate
//     row.price = selectedInventory.price
//     row.taxPrice = selectedInventory.itaxprice
//     row.locationName = selectedInventory.locationName
//     row.batchCode = selectedInventory.batchCode
//     row.maxQuantity=selectedInventory.qty
//     row.locationId=selectedInventory.locationId
//   }
// };

const calculateValues = (index: number) => {
  const row = formData.value[index];

 //数量
 const quantity = parseFloat(row.quantity.toString());
    //税率
    // const taxRate = parseFloat(row.taxRate.toString());
    const maxQuantity = parseFloat(row.maxQuantity.toString());

    if (quantity > maxQuantity) {
      ElMessage.warning(`数量不能超过 ${maxQuantity}`);
      row.quantity = maxQuantity;
    }

  // if (row.taxPrice && row.quantity) {
  //   //含税单价
  //   const taxPrice = parseFloat(row.taxPrice.toString());
   
  //   // 计算单价
  //   const price = taxPrice / (1 + taxRate);
  //   row.price = price.toFixed(2);

  //   // 计算金额
  //   const money = price * quantity;
  //   row.money = money.toFixed(2);

  //  // 计算价税合计
  //  const sum = taxPrice * quantity;
  //   row.sum = sum.toFixed(2);

  //   // 计算税额
  //   const tax = sum - (price * quantity);
  //   row.tax = tax.toFixed(2);
    

  // }
};

//批量新增代码

const formRefAdd = ref(null); // 确保变量名唯一

const openDialog = () => {
  if(props.saleOrderId==undefined)
  {
    ElMessage.warning(`请先选择销售订单`);
  }
  else if(props.warehouseId==undefined)
  {
    ElMessage.warning(`请先选择仓库订单`);
  }else{
  // 打开弹窗的逻辑
  formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }

};

const handleSuccess = (formData) => {

  // 处理 success 事件的逻辑
  console.log('Success event received with data:', formData)
  // 可以在这里调用 API 获取数据等
  const inventoryCodes = formData.inventoryCode;
  console.log('Selected inventory codes:', inventoryCodes);
  // 调用确认选择的方法
  confirmSelection(inventoryCodes);
};


/** 确认选择的存货编码 */
const confirmSelection = async (inventoryCodes: any[]) => {
  try {
    formLoading.value = true;
    const selectedInventoriesData = await Promise.all(inventoryCodes.map(async (id) => {
      const inventory = await StockApi.getStock(id);
      return {
        id: undefined,
        pid: props.pid,
        stockId: inventory.id,
        inventoryName: inventory.inventoryName,
        inventoryCode: inventory.inventoryCode,
        inventoryUnitName: inventory.inventoryUnitName,
        inventorySpecModel:inventory.inventorySpecModel,
        taxRate:inventory.taxRate,
        price:inventory.price,
        taxPrice:inventory.taxPrice,
        locationName:inventory.locationName,
        batchCode:inventory.batchCode,
        maxQuantity:inventory.qty,
        locationId:inventory.locationId,

       
      };
    }));
    formData.value.push(...selectedInventoriesData);
  } finally {
    formLoading.value = false;
    selectedInventories.value = []; // 重置选中的存货编码
  }
};

// 点击弹出框内容

const formRefAdd2 = ref(null); // 确保变量名唯一
const selectedRowIndex = ref(-1); // 用于存储被点击行的索引

const openDialog2 = (index) => {

  if(props.saleOrderId==undefined)
  {
    ElMessage.warning(`请先选择销售订单`);
  }
  else if(props.warehouseId==undefined)
  {
    ElMessage.warning(`请先选择仓库订单`);
  }else{
  selectedRowIndex.value = index;
  // 打开弹窗的逻辑
  formRefAdd2.value.open(event);
  // formRefAdd.value.open(); // 假设子组件有一个 open 方法
  }

 
};

const handleSuccess2 = (getFormData) => {
  // 处理 success 事件的逻辑
  console.log('Success event received with data:', getFormData)
  // 可以在这里调用 API 获取数据等
  // 调用确认选择的方法
  // confirmSelection2(inventoryCodes);
  console.log('selectedRowIndex.value:', selectedRowIndex.value)

  if (selectedRowIndex.value !== -1) {
    console.log(formData.value[selectedRowIndex.value])
    formData.value[selectedRowIndex.value] = { ...getFormData.value, ...getFormData };
  }
};


defineExpose({ validate, getData })
</script>